package kevin.hbase.monitor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;

/**
 * Hello world!
 */
public class HbaseCrud {
    private static Configuration conf = null;
    private static Connection conn = null;

    static {
        conf = HBaseConfiguration.create();
        try {
            conn = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 创建表
     *
     * @param tableName
     * @param familys
     * @throws Exception
     */
    public static void creatTable(String tableName, String[] familys) throws Exception {
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        if (admin.tableExists(tableName)) {
            System.out.println("table already exists");
        } else {
            HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tableName));
            for (int i = 0; i < familys.length; i++) {
                tableDesc.addFamily(new HColumnDescriptor(familys[i]));
            }
            admin.createTable(tableDesc);
            System.out.println("create table " + tableName + " ok.");
        }
    }

    /**
     * 删除表
     *
     * @param tableName
     * @throws Exception
     */
    public static void deleteTable(String tableName) throws Exception {
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        admin.disableTable(tableName);
        admin.deleteTable(tableName);
        System.out.println("delete table " + tableName + " ok.");
    }

    /**
     * 插入一行记录
     *
     * @param tableName
     * @param rowKey
     * @param family
     * @param qualifier
     * @param value
     * @throws Exception
     */
    public static void addRecord(String tableName, String rowKey, String family, String qualifier, String value)
            throws Exception {
        try {
            HTable table = (HTable) conn.getTable(TableName.valueOf(tableName));
            Put put = new Put(Bytes.toBytes(rowKey));
            put.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier), Bytes.toBytes(value));
            table.put(put);
            System.out.println("insert recored " + rowKey + " to table " + tableName + " ok.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除一行记录
     */
    public static void delRecord(String tableName, String rowKey) throws IOException {
        HTable table = (HTable) conn.getTable(TableName.valueOf(tableName));
        List<Delete> list = new ArrayList<Delete>();
        Delete del = new Delete(rowKey.getBytes());
        list.add(del);
        table.delete(list);
        System.out.println("del recored " + rowKey + " ok.");
    }

    /**
     * 查找一行记录
     */
    public static void getOneRecord(String tableName, String rowKey) throws IOException {
        HTable table = (HTable) conn.getTable(TableName.valueOf(tableName));
        Get get = new Get(rowKey.getBytes());
        Result rs = table.get(get);
        for (Cell cell : rs.listCells()) {
            // 一个Cell就是一个单元格，通过下面的方法可以获得这个单元格的各个值
            System.out.print("行健: " + new String(CellUtil.cloneRow(cell)));
            System.out.print("列簇: " + new String(CellUtil.cloneFamily(cell)));
            System.out.print(" 列: " + new String(CellUtil.cloneQualifier(cell)));
            System.out.print(" 值: " + new String(CellUtil.cloneValue(cell)));
            System.out.println("时间戳: " + cell.getTimestamp());
        }
    }

    /**
     * 显示所有数据
     */
    public static void getAllRecord(String tableName) {
        try {
            HTable table = (HTable) conn.getTable(TableName.valueOf(tableName));
            Scan s = new Scan();
            ResultScanner ss = table.getScanner(s);
            for (Result r : ss) {
                for (Cell cell : r.listCells()) {
                    System.out.print(Bytes.toString(CellUtil.cloneRow(cell)) + " ");
                    System.out.print(Bytes.toString(CellUtil.cloneFamily(cell)) + ":");
                    System.out.print(Bytes.toString(CellUtil.cloneQualifier(cell)) + " ");
                    System.out.println(Bytes.toString(CellUtil.cloneValue(cell)));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        try {
            String tablename = "scores";
            String[] familys = {"grade", "course"};
            HbaseCrud.creatTable(tablename, familys);

            //add record zkb
            HbaseCrud.addRecord(tablename, "zkb", "grade", "", "5");
            HbaseCrud.addRecord(tablename, "zkb", "course", "", "90");
            HbaseCrud.addRecord(tablename, "zkb", "course", "math", "97");
            HbaseCrud.addRecord(tablename, "zkb", "course", "art", "87");
            //add record  baoniu
            HbaseCrud.addRecord(tablename, "baoniu", "grade", "", "4");
            HbaseCrud.addRecord(tablename, "baoniu", "course", "math", "89");

            System.out.println("===========get one record========");
            HbaseCrud.getOneRecord(tablename, "zkb");

            System.out.println("===========show all record========");
            HbaseCrud.getAllRecord(tablename);

            System.out.println("===========del one record========");
            HbaseCrud.delRecord(tablename, "baoniu");
            HbaseCrud.getAllRecord(tablename);

            System.out.println("===========show all record========");
            HbaseCrud.getAllRecord(tablename);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}